package xyz.yuanjilu.service.impl;

import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import xyz.yuanjilu.service.MailService;
@Service
public class MailServiceImpl implements MailService{
    
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    // 邮件发送者的地址
    @Value("${mail.fromAddress}")
    private  String fromAddress;
    // 邮件发送者的中文昵称
    private  String personal = "招标信息服务";
    @Autowired
    private  JavaMailSenderImpl senderImpl;
    
    static{
    	//设置velocity资源加载器
        Properties prop = new Properties();  
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");  
        Velocity.init(prop);
    }

    @Override
    public void sendMail(String[] address,String subject, String templateName, Map templateData) {
        try {
            //建立邮件消息,发送简单邮件和html邮件的区别 
            MimeMessage mailMessage = senderImpl.createMimeMessage(); 
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "UTF-8");
            
            //设置收件人，寄件人 
            messageHelper.setTo(address); 
            messageHelper.setFrom(fromAddress,personal); 
            messageHelper.setSubject(subject); 
            
            
            VelocityContext context = new VelocityContext(templateData);
            
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(templateName, "UTF-8");
            tpl.merge(context, sw);
            
            String html = sw.toString();
            //true 表示启动HTML格式的邮件 
            messageHelper.setText(html, true); 
            
            //发送邮件 
            senderImpl.send(mailMessage);
            templateData.put("results", "ok");
            logger.info("邮件发送成功..");
        } catch (Exception e) {
            logger.error("发送邮件失败",e);
            templateData.put("results", "failed");
            templateData.put("message", e.getMessage());
        }
    }

    @Override
    public void sendMail(String address, String subject, String templateName, Map templateData) {
        String[] addresss={address};
       this.sendMail(addresss, subject, templateName, templateData);
    }
    
    
}
